<template>
 <div class="Countdown">
   <div class="Countdown-play" v-if="totalSeconds>0">
      倒计时:&nbsp;
      <span v-text="day"></span> &nbsp;天&nbsp;
      <span v-text="hour"></span> &nbsp;时&nbsp;
      <span v-text="minute"></span> &nbsp;分&nbsp;
      <span v-text="seconds"></span> &nbsp;秒&nbsp;
   </div>
   <div class="start" v-else>活动结束</div>
</div>
</template>

<script>
export default {
  name: "Countdown",
  props: {
    times: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      totalSeconds: 0,
      timeId: ""
    };
  },
  computed: {
    // 天
    day() {
      let d = Math.floor(this.totalSeconds / (3600 * 1000 * 24));
      return this.fillZero(d, 2);
    },
    // 时
    hour() {
      let temp = this.totalSeconds % (3600 * 1000 * 24);
      let h = Math.floor(temp / 3600 / 1000);
      return this.fillZero(h, 2);
    },
    // 分
    minute() {
      let temp = this.totalSeconds % (3600 * 1000);
      let m = Math.floor(temp / 60 / 1000);
      return this.fillZero(m, 2);
    },
    // 秒
    seconds() {
      let temp = this.totalSeconds % (60 * 1000);
      // console.log();
      let s = Math.floor(temp / 1000);
      return this.fillZero(s, 2);
    }
  },
  mounted() {
    console.log(this.totalSeconds, "this.totalSeconds");
    this.totalSeconds = this.times;
    this.play();
  },
  methods: {
    play() {
      clearInterval(this.timeId);
      this.timeId = setInterval(() => {
        if (this.totalSeconds == 0 || this.totalSeconds < 0) {
          clearInterval(this.timeId);
        } else {
          this.totalSeconds -= 1000;
        }
      }, 1000);
    },
    fillZero(data, num) {
      data = String(data);
      if (data.length >= num) {
        return data;
      } else {
        let temp = data;
        for (let i = 0; i < num - data.length; i++) {
          temp = 0 + temp;
        }
        return temp;
      }
    }
  },
  watch: {
    times(v) {
      this.totalSeconds = v;
      this.play();
      console.log(v, "this.totalSeconds");
    },
    totalSeconds(v) {
      // console.log('--log1--', v)
      if (v < 0) {
        this.$emit("end");
        // console.log('--log--', v)
      }
    }
  }
};
</script>
<style lang="scss">
.Countdown {
  .Countdown-play {
    display: flex;
    align-items: center;
    justify-content: center;
    span {
      display: block;
      background: rgba(0, 0, 0, 0.2);
      padding: 2px 5px;
      border-radius: 6px;
      box-sizing: border-box;
    }
  }
}
</style>

